package com.qf.java2105.huangchuang.hotel.controller;

import com.qf.java2105.huangchuang.hotel.constant.MessageConstant;
import com.qf.java2105.huangchuang.hotel.constant.ResponseMessageConstant;
import com.qf.java2105.huangchuang.hotel.factory.BeanFactory;
import com.qf.java2105.huangchuang.hotel.service.IFoodService;
import com.qf.java2105.huangchuang.hotel.service.IFoodTypeService;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.interfaces.RSAPrivateCrtKey;

/**
 * 控制层父类
 * @author hcvg
 * @version v1.0
 * @date 2021/09/13
 **/
public class BaseServlet extends HttpServlet {
    /**
     * 菜品业务层对象
     */
    public static IFoodService FOOD_SERVICE = (IFoodService) BeanFactory.getBean("foodService");
    /**
     * 菜系业务层对象
     */
    public static IFoodTypeService FOOD_TYPE_SERVICE = (IFoodTypeService) BeanFactory.getBean("foodTypeService");

    /**
     * 处理请求的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        try {
            String methodName = request.getParameter(ResponseMessageConstant.METHOD);
            // 反射获取调用此方法的对象内的method对应的方法
            //Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            Object result = method.invoke(this, request, response);
            if (result instanceof String){
                String info = (String) result;
                String url = info.substring(info.indexOf(ResponseMessageConstant.TAG) + 1);
                if (info.startsWith(ResponseMessageConstant.PREFIX_FORWARD)){
                    request.getRequestDispatcher(url).forward(request, response);
                }else if (info.startsWith(ResponseMessageConstant.PREFIX_REDIRECT)){
                    response.sendRedirect(url);
                }else {
                    response.getWriter().write(info);
                }
            }else {
                response.getWriter().write(MessageConstant.REQUEST_ERROR);
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
